from django.db import migrations


def allow_legacy_columns_nullable(apps, schema_editor):
    connection = schema_editor.connection
    table = "deal_transaction_result"
    with connection.cursor() as cursor:
        try:
            cursor.execute(f"SHOW COLUMNS FROM `{table}`")
            columns = cursor.fetchall()
        except Exception:
            columns = []

    # 允许存在但未在模型中的遗留列为可空且默认NULL
    allowed_fields = {
        "id",
        "sign_date",
        "contract_code",
        "contract_amount",
        "company_id",
        "project_id",
        "crawl_task_id",
        "created_at",
        "updated_at",
    }

    adjustments = []
    for field, _type, null_flag, _key, default_val, _extra in columns:
        if field in allowed_fields:
            continue
        # 将非模型列统一改为 NULL DEFAULT NULL
        if null_flag != "YES" or default_val is None:
            adjustments.append((field, _type))

    for field, dtype in adjustments:
        ddl = f"ALTER TABLE `{table}` MODIFY COLUMN `{field}` {dtype} NULL DEFAULT NULL"
        with connection.cursor() as cursor:
            cursor.execute(ddl)


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ('deal', '0005_fix_missing_core_columns'),
    ]

    operations = [
        migrations.RunPython(allow_legacy_columns_nullable, noop_reverse),
    ]